<!--
 * @Date: 2023-05-02 16:14:57
 * @LastEditTime: 2023-10-11 17:19:24
 * @FilePath: /wkw/src/views/swap-addLiquidity/index.vue
 * 介绍:增加流动性
-->

<route lang="json">
{
  "meta": {
    "title": "t('tian-jia-liu-dong-xing')"
  }
}
</route>
<script lang="ts" setup>
import { _require } from "@@/utils/tools";
import useBalanceStore from "@@/store/useBalanceStore";
import { toast, notify } from "@@/hooks/vantHooks";
import { fixedDecimals, normalNumber, omitText } from "@@/utils/tools/format";
import { sdkAddLiquidity, sdkEvaluationSwapTo } from "@@/sdk/web3Eth";
import { copyText } from "@@/utils/tools/project";
import { divide, multiply } from "mathjs";
import { parseAmount, parseBalance } from "@@/sdk/index";
import { useWkLpInfo, LpCoin } from "@@/views-tabbar/swap/wkLoopInfo";
import useTabPageStore from "@@/store/useTabPageStore";

const tabPageStore = useTabPageStore();

const contract_addr = computed(() => tabPageStore.homeData?.wkc.contract_addr);
const { lpCoinEnum } = useWkLpInfo([contract_addr.value!]);

const { t } = useI18n();
const balanceStore = useBalanceStore();

const coin0 = computed(() => balanceStore.getCoinByCode("USDT"));
const coin1 = computed(() => balanceStore.getCoinByCode("WKC"));

const lpCoin0 = computed<LpCoin | undefined>(
  () => lpCoinEnum.value[coin0.value?.id!]
);
const lpCoin1 = computed<LpCoin | undefined>(
  () => lpCoinEnum.value[coin1.value?.id!]
);
const addRatio = computed(() =>
  divide(Number(lpCoin0.value?.totalAmount), Number(lpCoin1.value?.totalAmount))
);

function loadPage() {
  balanceStore.findBalance(coin0.value!);
  balanceStore.findBalance(coin1.value!);
  balanceStore.findApprove(coin0.value, balanceStore.approveAddresss);
  balanceStore.findApprove(coin1.value, balanceStore.approveAddresss);
}
loadPage();
onActivated(loadPage);

const coin0Approve = computed(() =>
  balanceStore.checkApprove(coin0.value, Number(formData.amount0))
);

const coin1Approve = computed(() =>
  balanceStore.checkApprove(coin1.value, Number(formData.amount1))
);

const formData = reactive({
  amount0: "",
  amount1: "",
});
let lastInput = () => {};

function inputAmount0() {
  //是lp创始人
  if (!tabPageStore.homeData?.address.pair_address) return;
  const fromValue = Number(
    parseAmount(Number(formData.amount0), coin0.value?.format!)
  );

  const value1 = multiply(fromValue, addRatio.value);
  formData.amount1 = normalNumber(parseBalance(value1, coin1.value?.format!));
  lastInput = inputAmount0;
}
function inputAmount1() {
  //是lp创始人
  if (!tabPageStore.homeData?.address.pair_address) return;
  const value1 = Number(
    parseAmount(Number(formData.amount1), coin1.value?.format!)
  );
  const fromValue = divide(value1, addRatio.value);
  formData.amount0 = normalNumber(
    parseBalance(fromValue, coin0.value?.format!)
  );
  lastInput = inputAmount1;
}
watch(
  () => lpCoinEnum.value,
  () => lastInput(),
  { deep: true }
);

/**按钮加载状态 */
const btnLoading = reactive({
  submitBtn: false,
  approveCoin1Btn: false,
  approveCoin0Btn: false,
});

async function submitBtn() {
  const amount0 = Number(formData.amount0);
  const amount1 = Number(formData.amount1);
  const coin_0 = coin0.value!;
  const coin_1 = coin1.value!;
  const mini = 0;
  if (!(amount0 > mini))
    return toast.text(
      `${coin_0.code}${t("shu-liang-bu-neng-xiao-yu")} ${mini}`
    );
  if (!(amount1 > mini))
    return toast.text(
      `${coin_1.code}${t("shu-liang-bu-neng-xiao-yu")} ${mini}`
    );
  btnLoading.submitBtn = true;
  const [fromBalance, toBalance] = await Promise.all([
    balanceStore.findBalance(coin_0!),
    balanceStore.findBalance(coin_1!),
  ]);
  btnLoading.submitBtn = false;

  if (!(amount0 <= Number(fromBalance)))
    return toast.text(`${coin_0.code}${t("yu-e-bu-zu")}`);
  if (!(amount1 <= Number(toBalance)))
    return toast.text(`${coin_1.code}${t("yu-e-bu-zu")}`);
  await addLiquidity(amount0, amount1, coin_0, coin_1);
  balanceStore.findBalance(coin_0);
  balanceStore.findBalance(coin_1);
}
/**添加流动性 */
async function addLiquidity(
  amount0: number,
  amount1: number,
  coin0: CoinPay,
  coin1: CoinPay
) {
  btnLoading.submitBtn = true;
  const res = await sdkAddLiquidity(
    [coin0.contract_addr!, coin1.contract_addr!],
    [amount0, amount1],
    [coin0.format, coin1.format],
    balanceStore.approveAddresss
  );
  btnLoading.submitBtn = false;
  if (!res.status) return notify.error(res.message);
  return notify.success(`${t("tian-jia-cheng-gong")} ${omitText(res.data)}`, {
    onClick() {
      copyText(res.data!);
    },
  });
}
async function approveCoin1Btn() {
  btnLoading.approveCoin1Btn = true;
  await balanceStore.approve(
    coin1.value,
    undefined,
    balanceStore.approveAddresss
  );
  btnLoading.approveCoin1Btn = false;
}

async function approveCoin0Btn() {
  btnLoading.approveCoin0Btn = true;
  await balanceStore.approve(
    coin0.value,
    undefined,
    balanceStore.approveAddresss
  );
  btnLoading.approveCoin0Btn = false;
}
const price = ref<string>();
getPrice();
async function getPrice() {
  const res = await sdkEvaluationSwapTo(
    1,
    [coin0.value?.contract_addr!, coin1.value?.contract_addr!],
    [coin0.value?.format!, coin1.value?.format!],
    balanceStore.approveAddresss
  );
  if (res.status) {
    price.value = res.data;
  }
}
const radioBtns = computed(() => [
  {
    text: "25%",
    value0: multiply(Number(coin0.value?.balance || 0), 0.25).toString(),
    value1: multiply(Number(coin1.value?.balance || 0), 0.25).toString(),
  },
  {
    text: "50%",
    value0: multiply(Number(coin0.value?.balance || 0), 0.5).toString(),
    value1: multiply(Number(coin1.value?.balance || 0), 0.5).toString(),
  },
  {
    text: "75%",
    value0: multiply(Number(coin0.value?.balance || 0), 0.75).toString(),
    value1: multiply(Number(coin1.value?.balance || 0), 0.75).toString(),
  },
  {
    text: "MAX",
    value0: coin0.value?.balance || "0",
    value1: coin1.value?.balance || "0",
  },
]);
</script>

<template>
  <CpageView>
    <div class="auto-MT-md">
      <Ccard class="PB-xxl">
        <div class="auto-MT-md">
          <div class="flex-A-C auto-ML-xs">
            <div class="flex-A-C">
              <Rimage size="42rem" :src="coin0?.logo" />
              <div class="ML-xs">{{ coin0?.code }}</div>
            </div>
          </div>
          <Rinput
            class="T-S-xxl"
            label-align="top"
            @input="inputAmount0"
            type="number"
            v-model="formData.amount0"
            :border-mode="'bottom'"
            :placeholder="'0.00'"
          >
            <template #button>
              <div class="T-S-sm">
                <span>{{ $t("yue") }} </span>
                <span>{{ fixedDecimals(coin0?.balance, 4) }}</span>
              </div>
            </template>
          </Rinput>
          <RradioBtnGroup v-model="formData.amount0" @change="inputAmount0">
            <RradioBtn :value="item.value0" v-for="item in radioBtns">
              {{ item.text }}
            </RradioBtn>
          </RradioBtnGroup>
        </div>
      </Ccard>
      <div class="swapBtn">
        <van-icon class="Cicon" color="var(--C-LG1)" name="plus" />
      </div>
      <!-- 接收币种 -->
      <Ccard class="PT-xxl MT-0">
        <div class="auto-MT-md">
          <div class="flex-A-C">
            <Rimage size="42rem" :src="coin1?.logo" />
            <div class="ML-xs">{{ coin1?.code }}</div>
          </div>
          <Rinput
            class="T-S-xxl"
            v-model="formData.amount1"
            label-align="top"
            @input="inputAmount1"
            type="number"
            :border-mode="'bottom'"
            :placeholder="'0.00'"
          >
            <template #button>
              <div class="T-S-sm">
                <span>{{ $t("yue") }}</span>
                <span>{{ fixedDecimals(coin1?.balance, 4) }}</span>
              </div>
            </template>
          </Rinput>
          <RradioBtnGroup v-model="formData.amount1" @change="inputAmount1">
            <RradioBtn :value="item.value1" v-for="item in radioBtns">
              {{ item.text }}
            </RradioBtn>
          </RradioBtnGroup>
        </div>
      </Ccard>
      <TransitionGroup name="page">
        <Rbutton
          key="1"
          class="MT-md"
          v-if="!coin0Approve"
          @click="approveCoin0Btn"
          :loading="btnLoading.approveCoin0Btn"
          bg="var(--C-LG1)" borderStyle="none"
          :size="'large'"
          block
        >
          <span>{{ $t("pi-zhun") }}</span
          ><span>{{ coin0?.code }}</span>
        </Rbutton>
        <Rbutton
          key="2"
          class="MT-md"
          v-if="!coin1Approve"
          @click="approveCoin1Btn"
          :loading="btnLoading.approveCoin1Btn"
          bg="var(--C-LG1)" borderStyle="none"
          :size="'large'"
          block
        >
          <span>{{ $t("pi-zhun") }}</span
          ><span>{{ coin1?.code }}</span>
        </Rbutton>
        <Rbutton
          key="3"
          class="MT-md"
          v-if="coin0Approve && coin1Approve"
          @click="submitBtn"
          :loading="btnLoading.submitBtn"
          bg="var(--C-LG1)" borderStyle="none"
          :size="'large'"
          block
        >
          {{ $t("gong-ying") }}
        </Rbutton>
      </TransitionGroup>
    </div>
  </CpageView>
</template>

<style lang="scss" scoped>
.rotate {
  transform: rotate(180deg);
}
.transition {
  transition: transform 200ms linear;
}
.swapBtn {
  $offset: -24rem;
  margin-top: $offset;
  margin-bottom: $offset;
  text-align: center;
  .Cicon {
    padding: var(--gap-sm);
    border-radius: 9999rem;
    background-color: var(--C-B1);
    border: solid 1rem var(--C-T1-O1);
    font-size: 26rem;
  }
}
</style>
